import sqlite3

class SQLiteHandler:
    def __init__(self):
        self.conn = 0
    def SQLiteConnect(self):
        conn = sqlite3.connect('data.db')        self.conn = conn
        return conn
    def DoQuery(self,query):
        cursor = self.conn.cursor()
        cursor.execute(query)
        q = cursor.fetchall()
        self.conn.commit()
        cursor.close()
        return q
    def Close(self):
        self.conn.close()

sqlite = SQLiteHandler()
conn = sqlite.SQLiteConnect()

def Update(equery):
    global sqlite, conn
    sqlite.DoQuery(equery)
    
def Select(equery):
    global sqlite, conn
    query = sqlite.DoQuery(equery)
    return query

def Login(user, passwd):
    usr = Select("SELECT user from user where user='"+user+"';")
    if usr == []:
        return "Kein Username " + user + " vorhanden", False
    pwd = Select("SELECT password from user where user='"+user+"';")
    pwd = str(pwd[0][0])
    pwd = str.decode(pwd,'base64')
    print pwd
    if pwd != passwd:
        return "Du hast das falsche Passwort eingegeben", False
    return "Erfolgreich eingeloggt!",True

def CreateAccount(user,passwd,email):
    if Select("SELECT user from user where user='"+user+"';") == []:
        Update("INSERT INTO user (user, password, email) VALUES ('"+user+"','"+str.encode(passwd,'base64')+"','"+email+"')")
        return "Account erfolgreich angelegt!", True
    else:
        return "Der Username \""+user+"\" ist schon vergeben!", False
def Close():
    mysql.Close()

